//
//  QAViewController.m
//  HelloWorld
//
//  Created by MJiao on 15/6/24.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "QAViewController.h"

#include "AFHTTPRequestOperationManager.h"
#import "QuestionPageModel.h"
#import "Question.h"
#import "QuestionTableViewCell.h"
#import "QuestionDetailViewController.h"
#import "ImgeUtil.h"
#import "UserManager.h"
#import "KVNProgress.h"
#import "CommonUtils.h"

#import "UIImageView+AFNetworking.h"
#import "MingShiTencentSessionDelegate.h"
#import "AFHTTPRequestOperation.h"
#import "PostAnswerViewController.h"
#import "DataSourceManager.h"

@interface QAViewController ()

/** 用来显示的假数据 */
@property(strong, nonatomic) QuestionPageModel *answerPageModel;
@property(strong, nonatomic) Question *didSelectedQuestion;
@property(strong, nonatomic) QuestionTableViewCell *cellPrototype;
@property(strong, nonatomic) NSMutableArray *gradeViewArray;
@property(strong, nonatomic) NSMutableArray *subjectViewArray;
@property(nonatomic, copy) NSString *selectedGradeName;
@property(nonatomic, copy) NSString *selectedSubjectName;
@property(strong, nonatomic) NSMutableDictionary *rowHeightDictionary;

@end

@implementation QAViewController
- (IBAction)btnSelectSubject:(id)sender {
    isViewSelectSubjectShow = !isViewSelectSubjectShow;
    [self switchSelectSubjectShowView];
}


/**
*  选择年级
*
*  @param sender <#sender description#>
*/
- (IBAction)btnSelectGradeAction:(id)sender {
    UIButton *btnGrade = ((UIButton *) sender);
    NSString *title = [[btnGrade titleLabel] text];

    self.selectedGradeName = title;

    for (UIButton *btn in  self.gradeViewArray) {
        if ([[[btn titleLabel] text] isEqualToString:title]) {
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
        }
    }
}

/**
*   选择学科
*
*  @param sender <#sender description#>
*/
- (IBAction)btnSubjectSelectAction:(id)sender {

    UIButton *btnSubject = ((UIButton *) sender);
    NSString *title = [[btnSubject titleLabel] text];
    self.selectedSubjectName = title;

    for (UIButton *btn in  self.subjectViewArray) {
        if ([[[btn titleLabel] text] isEqualToString:title]) {
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
        }
    }
}

/**
*  确认选择
*
*  @param sender <#sender description#>
*/
- (IBAction)btnConfirmSelectAction:(id)sender {
    isViewSelectSubjectShow = !isViewSelectSubjectShow;
    [self switchSelectSubjectShowView];
    NSString *title = @"帮帮";
    if ([self.selectedSubjectName isEqualToString:@"全部"] && [self.selectedGradeName isEqualToString:@"全部"]) {
        title = @"全部问题";
    } else {
        title = [NSString stringWithFormat:@"%@%@", self.selectedGradeName, self.selectedSubjectName];
    }
    NSLog(@"新的Title:%@", title);
    [self.lbSelectCategoryTitle setText:title];
//    self.lbSelectCategoryTitle setText
//    [self.btnSelectCategory setTitle:title forState:UIControlStateNormal];
//    [self.btnSelectCategory setTitle:title forState:UIControlStateHighlighted];
//    [self.btnSelectCategory setTitle:title forState:UIControlStateSelected];

    //先清空数据源
    [self.answerPageModel.dataArray removeAllObjects];

    //开始加载
    [self.tableView.header beginRefreshing];
}

- (void)initSubjectAndGradeSelectViewState {
    NSArray *views = [self.viewSelectSubject subviews];
    UIView *containerView = [views objectAtIndex:0];
    for (UIView *subview in [containerView subviews]) {
        if ([subview isKindOfClass:[UIButton class]] && subview.tag >= 0 && subview.tag <= 19) {
            UIButton *btnGrade = (UIButton *) subview;
            //0 0.478431 1 1
//            NSLog(@"btnGrade:%@", [btnGrade currentTitleColor]);
            if (subview.tag == 0 || subview.tag == 10) {
                [btnGrade setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
            } else {
                [btnGrade setTitleColor:[UIColor colorWithRed:0.333333 green:0.333333 blue:0.333333 alpha:1] forState:UIControlStateNormal];
            }
        }

    }
}

- (void)recvPostAnswerActionNotification:(NSNotification *)notification {
    //第一步，进行登陆检查判断
    //检查当前用户是否已经登录
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }
    Question *question = [[notification userInfo] objectForKey:@"question"];
    self.didSelectedQuestion = question;
    [self performSegueWithIdentifier:@"ToPostAnswerSegue" sender:self];

    // afd
}

- (void)recvNewDataNotify:(NSNotification *)notification {
    self.isWillReloadData = YES;
}

/**
* 接收百度push注册通知
*/
- (void)recvBaiduPushNotify:(NSNotification *)notification {
    [self processAutoLogin];
}

- (void)processPushNotifyBadge:(NSNotification *)notification {
    [self processPushNotifyBadge];
}

- (void)refreshWhenAppear
{
    self.isWillReloadData = YES;
}


- (void)processPushNotifyBadge {
    if ([[DataSourceManager shareDataSourceManager] notifyCount] == 0) {
        [[self.tabBarController.tabBar.items objectAtIndex:2] setBadgeValue:nil];
    } else {
        NSString *strNotifyNum = [NSString stringWithFormat:@"%ld", (unsigned long)[[DataSourceManager shareDataSourceManager] notifyCount]];
        [[self.tabBarController.tabBar.items objectAtIndex:2] setBadgeValue:strNotifyNum];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];

    BOOL isNotFirstUseApp = [[NSUserDefaults standardUserDefaults] boolForKey:@"isNotFirstUseApp"];
    if (!isNotFirstUseApp) {
        [self showUserGudieView];
        return;
    }

    [self doViewDidWork];
    [self.viewSelectSubject addObserver:self forKeyPath:@"frame" options:0x01 context:nil];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
}

- (void)doViewDidWork {
    [self assembleSubjectViewArray];
    [self assembleGradeViewArray];


    NSLog(@"******************************");
    NSLog(@"[UIScreen mainScreen].scale:%f", [UIScreen mainScreen].scale);
    NSLog(@"******************************");

    self.selectedGradeName = @"全部";
    self.selectedSubjectName = @"全部";

    self.rowHeightDictionary = [[NSMutableDictionary alloc] init];


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recvNewDataNotify:)
                                                 name:@"newDataNotify"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recvBaiduPushNotify:)
                                                 name:@"recvBaiduPushNotify"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(processPushNotifyBadge:)
                                                 name:@"processPushNotifyBadge"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshWhenAppear)
                                                 name:@"NeedRefreshQuestionNotify"
                                               object:nil];



//
//    return;

    // Do any additional setup after loading the view.
//    NSLog(@"QAViewController viewDidLoad");
    isViewSelectSubjectShow = FALSE;
    [self switchSelectSubjectShowView];
    [self initSubjectAndGradeSelectViewState];

//
//    NSString *CellIdentifier = @"AnswerTableViewCellIdentifier";
//    [self.tableView registerNib:[UINib nibWithNibName:@"QuestionTableViewCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
//    self.cellPrototype = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

//    self.navigationItem.titleView = nil;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recvPostAnswerActionNotification:)
                                                 name:@"postAnswerAction"
                                               object:nil];


    self.tableView.estimatedRowHeight = 347;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    /**
    *  初始化数据集
    */
    if (!self.answerPageModel) {
        self.answerPageModel = [[QuestionPageModel alloc] init];
        self.answerPageModel.dataArray = [[NSMutableArray alloc] init];
    }
    [self.tableView setHidden:NO];

    /**
    *  去掉TableView每个cell之间的默认分割线
    */
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.answerPageModel.currentPage = 1;
        [self processNetRequest];
    }];
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.answerPageModel.currentPage += 1;
        [self processNetRequest];
    }];

    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableView.footer.autoChangeAlpha = YES;
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableView.header.autoChangeAlpha = YES;

    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];


//    [self processAutoLogin];
}

- (void)assembleSubjectViewArray {
    self.subjectViewArray = [[NSMutableArray alloc] init];

    NSArray *containerRow3View = [self.subjectRowView1ContainerView subviews];
    for (UIView *subview in containerRow3View) {
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;

            [self.subjectViewArray addObject:btn];
        }
    }
    NSArray *containerRow4View = [self.subjectRowView2Container subviews];
    for (UIView *subview in containerRow4View) {
        UIView *btnView = [[subview subviews] objectAtIndex:0];

        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;

            [self.subjectViewArray addObject:btn];
        }
    }

}

- (void)assembleGradeViewArray {

    self.gradeViewArray = [[NSMutableArray alloc] init];

    NSArray *containerRow1View = [self.gradeRowView1ContainerView subviews];
    for (UIView *subview in containerRow1View) {
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;
            //  NSLog(@"containerRow1View.title:%@", [[btn titleLabel] text]);
            [self.gradeViewArray addObject:btn];
        }
    }
    NSArray *containerRow2View = [self.gradeRowView2ContainerView subviews];
    for (UIView *subview in containerRow2View) {
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;
            //  NSLog(@"containerRow2View.title:%@", [[btn titleLabel] text]);
            [self.gradeViewArray addObject:btn];
        }
    }
}

- (void)showUserGudieView {

    UIWindow *mWindow = [[[UIApplication sharedApplication] delegate] window];

    CGRect ScreenRect = [[UIScreen mainScreen] bounds];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenRect.size.width, ScreenRect.size.height)];
    [mWindow addSubview:scrollView];

    for (int i = 0; i < 3; i++) {
        NSString *string = [NSString stringWithFormat:@"userGuide0%i.png", i + 1];
        UIImage *forImage = [UIImage imageNamed:string];
        UIImageView *ForImageView = [[UIImageView alloc] initWithImage:forImage];
        ForImageView.frame = CGRectMake(ScreenRect.size.width * i, 0, ScreenRect.size.width, ScreenRect.size.height);
        [scrollView addSubview:ForImageView];
    }
    [scrollView setTag:1000000];

    //设置滚动视图的内容的大小
    scrollView.contentSize = CGSizeMake(ScreenRect.size.width * 3, 0);

    scrollView.bounces = NO;

    //设置分页
    scrollView.pagingEnabled = YES;

    //再最后一页上 设置一个button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    /**
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage: [UIImage imageNamed:@"btnStart.png"] forState:UIControlStateNormal];

    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    */
    UIImage *btnStartImg = [UIImage imageNamed:@"btnStart.png"];
    [button setImage:btnStartImg forState:UIControlStateNormal];

    float factor = [UIScreen mainScreen].scale;

    float x = ScreenRect.size.width * 2 + (ScreenRect.size.width / 2 - btnStartImg.size.width / factor / 2);
    button.frame = CGRectMake(x, 370, 120, 50);
    [button addTarget:self action:@selector(btnEnterApp) forControlEvents:UIControlEventTouchUpInside];
    //button.backgroundColor = [UIColor cyanColor];

    [scrollView addSubview:button];

    [scrollView setShowsHorizontalScrollIndicator:NO];

}

/**
*   进入游戏
*/
- (void)btnEnterApp {
    // NSLog(@"Start work...");
    UIWindow *mWindow = [[[UIApplication sharedApplication] delegate] window];
    NSArray *subViewArray = [mWindow subviews];
    for (UIView *subView in subViewArray) {
        if (subView.tag == 1000000) {
            [subView removeFromSuperview];
        }
    }
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isNotFirstUseApp"];

    [self doViewDidWork];
}

/**
* 处理网络请求
*/
- (void)processNetRequest {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSString *encodedSelectedGradeName = [self.selectedGradeName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *encodedSelectedSubjectName = [self.selectedSubjectName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


    NSInteger cacheUserId = [[[UserManager shareUserManager] curUser] cacheUserId];
    NSLog(@">>>>>cacheUserId:%ld", cacheUserId);


//    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/help/querys?isopen=0&currentPage=%ld&gradeName=%@&subjectName=%@", self.answerPageModel.currentPage, encodedSelectedGradeName, encodedSelectedSubjectName];
    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/help/querys?isopen=0&currentPage=%ld&gradeName=%@&subjectName=%@&userId=%ld", self.answerPageModel.currentPage, encodedSelectedGradeName, encodedSelectedSubjectName, cacheUserId];

    NSLog(@"帮帮URL:%@", urlString);

    [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束刷新
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];

        NSInteger currentPage = [[responseObject objectForKey:@"currentPage"] integerValue];
        NSInteger allPage = [[responseObject objectForKey:@"allPage"] integerValue];

        self.answerPageModel.currentPage = currentPage;
        self.answerPageModel.allPage = allPage;


        NSLog(@"responseObject:%@", responseObject);

        /**
        *  如果是下拉刷新则需要情况之前缓冲中的数据
        */
        if (self.answerPageModel.currentPage == 1) {
            [self.answerPageModel.dataArray removeAllObjects];
        }


        NSArray *result = [responseObject objectForKey:@"result"];
        [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *title = [obj objectForKey:@"title"];
            NSInteger userId = [[obj objectForKey:@"userId"] integerValue];
            NSInteger replyCount = [[obj objectForKey:@"plnum"] integerValue];
            NSString *imageUrl = [obj objectForKey:@"imageUrl"];
            NSInteger answerId = [[obj objectForKey:@"id"] integerValue];
            NSString *contents = [obj objectForKey:@"contents"];
            NSString *status = [obj objectForKey:@"status"];
            NSString *createTime = [obj objectForKey:@"createtime"];
            NSString *subjectName = [obj objectForKey:@"subjectName"];
            NSString *gradeName = [obj objectForKey:@"gradeName"];
            NSString *userImage = [obj objectForKey:@"userImage"];
            NSString *sex = [obj objectForKey:@"sex"];
            NSString *userName = [obj objectForKey:@"userName"];
            NSLog(@"********userName:%@", userName);
            NSString *slogins = [obj objectForKey:@"slogins"];
            NSString *isgood = [obj objectForKey:@"isgood"];
            NSInteger questionId = [[obj objectForKey:@"id"] integerValue];

            NSLog(@"********isgood:%@", isgood);
            NSString *resizedImageUrl = [obj objectForKey:@"resizedImageUrl"];

            NSInteger imageWidth = [[obj objectForKey:@"imageWidth"] integerValue];
            NSInteger imageHeight = [[obj objectForKey:@"imageHeight"] integerValue];

            NSInteger resizedImageWidth = [[obj objectForKey:@"resizedImageWidth"] integerValue];
            NSInteger resizedImageHeight = [[obj objectForKey:@"resizedImageHeight"] integerValue];


            Question *answer = [[Question alloc] init];
            answer.title = title;
            answer.userId = userId;
            answer.imageUrl = imageUrl;
            answer.contents = contents;
            answer.status = status;
            answer.createTime = createTime;
            answer.subjectName = subjectName;
            answer.gradeName = gradeName;
            answer.answerId = answerId;
            answer.replyCount = replyCount;
            answer.userName = userName;
            answer.userImage = userImage;
            answer.slogins = slogins;
            answer.sex = sex;
            answer.imageWidth = imageWidth;
            answer.imageHeight = imageHeight;
            answer.resizedImageWidth = resizedImageWidth;
            answer.resizedImageHeight = resizedImageHeight;
            answer.resizedImageUrl = resizedImageUrl;
            answer.questionId = questionId;
            answer.isgood = isgood;


            [self.answerPageModel.dataArray addObject:answer];
        }];
        //刷新table.footer显示状态
        [self refreshTableFooterShowStatus];
        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //NSLog(@"Error: %@", error);


        self.answerPageModel.currentPage--;
        if (self.answerPageModel.currentPage <= 1) {
            self.answerPageModel.currentPage = 1;
        }

        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];

        // 结束刷新
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    //刷新table.footer显示状态
    [self refreshTableFooterShowStatus];

    if (self.isWillReloadData) {
        self.isWillReloadData = NO;
        [self.tableView.header beginRefreshing];
    }
}

- (void)refreshTableFooterShowStatus {
    if (self.answerPageModel == nil || self.answerPageModel.dataArray == nil || [self.answerPageModel.dataArray count] == 0) {
        [self.tableView.footer setHidden:YES];
    } else {
        [self.tableView.footer setHidden:NO];
    }
}

/**
*  处理自动登录
*
*/
- (void)processAutoLogin {
    if ([[UserManager shareUserManager] isALastLoginByQQ]) {
        [self processAutoLoginByThirdAccount];
    }
    else if ([[UserManager shareUserManager] isAutoLogin]) {

        [self processAutoLoginByCommonAccount];


    }

}

- (void)processAutoLoginByThirdAccount {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *openId = [userDefaults stringForKey:@"openId"];
    if (openId == nil || openId.length == 0) {
        return;
    }

    /**
    * 验证用户是否绑定了账号
    */
    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/users/verifyRegisterByQQ?openId=%@&channelId=%@&deviceType=4", openId, [[UserManager shareUserManager] bdPushChannelId]];

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code != nil && [code isEqualToString:@"00"]) {
            //  [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            NSArray *result = [responseObject objectForKey:@"result"];
            [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSString *loingName = [obj objectForKey:@"loingName"];
                NSString *sex = [obj objectForKey:@"sex"];
                NSString *address = [obj objectForKey:@"address"];
                NSString *creatTime = [obj objectForKey:@"creatTime"];
                NSString *wenwen = [obj objectForKey:@"wenwen"];
                NSString *moneys = [obj objectForKey:@"moneys"];
                NSString *imageUrl = [obj objectForKey:@"imageUrl"];
                NSString *gradeName = [obj objectForKey:@"gradeName"];
                NSString *schoolName = [obj objectForKey:@"schoolName"];
                NSString *email = [obj objectForKey:@"email"];
                NSString *slogins = [obj objectForKey:@"slogins"];
                NSString *userName = [obj objectForKey:@"userName"];
                NSInteger userId = [[obj objectForKey:@"id"] integerValue];
                NSInteger twnum = [[obj objectForKey:@"twnum"] integerValue];
                NSString *openId = [obj objectForKey:@"openId"];
                NSString *accessToken = [obj objectForKey:@"accessToken"];
                NSString *themeImage = [obj objectForKey:@"themeImage"];
                NSInteger age = 0;


                @try {
                    age = [[obj objectForKey:@"brith"] integerValue];
                }
                @catch (NSException *exception) {
                    NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
                }
                User *user = [[User alloc] init];
                user.account = loingName;
                //user.pwd = pwd;
                user.sex = sex;
                user.address = address;
                user.creatTime = creatTime;
                user.wenwen = wenwen;
                user.moneys = moneys;
                user.imageUrl = imageUrl;
                user.gradeName = gradeName;
                user.schoolName = schoolName;
                user.email = email;
                user.slogins = slogins;
                user.userName = userName;
                user.userId = userId;
                user.twnum = twnum;
                user.openId = openId;
                user.accessToken = accessToken;
                user.age = age;
                user.themeImage = themeImage;

                [[UserManager shareUserManager] setCurUser:user];
                //保存登录信息
                [[UserManager shareUserManager] saveUserToDisk:user];
            }];
            [KVNProgress showSuccessWithStatus:@"登录成功" completion:^{
                // Things you want to do after the HUD is gone.
                [self.navigationController popToRootViewControllerAnimated:YES];
                [self processPushNotifyBadge];
            }];
        }



    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}


- (void)processAutoLoginByCommonAccount {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    NSString *account = [userDefaults objectForKey:@"account"];
    NSString *pwd = [userDefaults objectForKey:@"pwd"];

    if (account == nil || account.length == 0) {
        return;
    }

    account = [account stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/users/login?loingName=%@&pssword=%@&channelId=%@&deviceType=4", account, pwd, [[UserManager shareUserManager] bdPushChannelId]];


    NSLog(@"urlString:%@", urlString);

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }

        NSLog(@"responseObject:%@", responseObject);

        NSArray *result = [responseObject objectForKey:@"result"];
        [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *loingName = [obj objectForKey:@"loingName"];
            NSString *sex = [obj objectForKey:@"sex"];
            NSString *address = [obj objectForKey:@"address"];
            NSString *creatTime = [obj objectForKey:@"creatTime"];
            NSString *wenwen = [obj objectForKey:@"wenwen"];
            NSString *moneys = [obj objectForKey:@"moneys"];
            NSString *imageUrl = [obj objectForKey:@"imageUrl"];
            NSString *gradeName = [obj objectForKey:@"gradeName"];
            NSString *schoolName = [obj objectForKey:@"schoolName"];
            NSString *email = [obj objectForKey:@"email"];
            NSString *slogins = [obj objectForKey:@"slogins"];
            NSString *userName = [obj objectForKey:@"userName"];
            NSInteger userId = [[obj objectForKey:@"id"] integerValue];
            NSInteger twnum = [[obj objectForKey:@"twnum"] integerValue];
            NSString *themeImage = [obj objectForKey:@"themeImage"];
            NSInteger age = 0;

            @try {
                age = [[obj objectForKey:@"brith"] integerValue];
            }
            @catch (NSException *exception) {
                NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
            }


            User *user = [[User alloc] init];
            user.account = loingName;
            user.pwd = pwd;
            user.sex = sex;
            user.address = address;
            user.creatTime = creatTime;
            user.wenwen = wenwen;
            user.moneys = moneys;
            user.imageUrl = imageUrl;
            user.gradeName = gradeName;
            user.schoolName = schoolName;
            user.email = email;
            user.slogins = slogins;
            user.userName = userName;
            user.userId = userId;
            user.twnum = twnum;
            user.age = age;
            user.themeImage = themeImage;

            [[UserManager shareUserManager] setCurUser:user];
            //保存登录信息
            [[UserManager shareUserManager] saveUserToDisk:user];
        }];
        [KVNProgress showSuccessWithStatus:@"自动登录成功" completion:^{
            // Things you want to do after the HUD is gone.
            [self.navigationController popToRootViewControllerAnimated:YES];
            [self processPushNotifyBadge];
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络错误,自动登录失败"];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.answerPageModel.dataArray.count;

//    return self.answerPageModel.dataArray.count > 0 ?1 :0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"QuestionTableViewCell";

    QuestionTableViewCell *answerTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];


    if (answerTableViewCell == nil) {
        answerTableViewCell = [[QuestionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        //将Custom.xib中的所有对象载入
//        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QuestionTableViewCell" owner:nil options:nil];
//        //第一个对象就是CustomCell了
//        answerTableViewCell = [nib objectAtIndex:0];
    }


    NSLog(@"**********[ answerTableViewCell.bounds.size.height + 1]:%f", (answerTableViewCell.bounds.size.height + 1));
    
    
    Question *question = [self.answerPageModel.dataArray objectAtIndex:[indexPath row]];

    NSString *gradeAndSubject = question.subjectName;

    //[NSString stringWithFormat:@"%@/%@:", answer.gradeName, answer.subjectName];

    [answerTableViewCell.lbGradeName setText:question.gradeName];

    [answerTableViewCell setQuestion:question];

    NSString *reply = [NSString stringWithFormat:@"%ld回复", (unsigned long) question.replyCount];

    NSString *status = @"待解决";
    /**
    *  status: 0表示待解决,1表示已解决
    */
    if ([question.status isEqualToString:@"0"]) {
        status = @"待解决";
        [answerTableViewCell.ivRsolveFlag setImage:[UIImage imageNamed:@"usercard_list_ask"]];
    } else if ([question.status isEqualToString:@"1"]) {
        status = @"已解决";
        [answerTableViewCell.ivRsolveFlag setImage:[UIImage imageNamed:@"vote_has_voted"]];
    }

    [answerTableViewCell.lbSubject setText:gradeAndSubject];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    //"createtime": "2015-07-09 17:32:43",
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];

    NSString *createTime = question.createTime;
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:question.createTime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }
    [answerTableViewCell.lbPostTime setText:createTime];
    [answerTableViewCell.lbReply setText:reply];
    [answerTableViewCell.lbStatus setText:status];
    [answerTableViewCell.lbTitle setText:question.contents];
    [answerTableViewCell.lbUserName setText:[CommonUtils serializableIdObject:question.userName defaultValue:@""]];


    [answerTableViewCell.lbUserImage setImageWithURL:[NSURL URLWithString:[CommonUtils serializableIdObject:question.userImage defaultValue:@""]] placeholderImage:[UIImage imageNamed:@"user_default_portrait_38"]];

    //圆角
    answerTableViewCell.lbUserImage.layer.masksToBounds = YES;
    answerTableViewCell.lbUserImage.layer.cornerRadius = 15;


    UIImageView *ivScreenshot = answerTableViewCell.ivScreenshot;

//    684
    NSLog(@"answerTableViewCell.frame.size.width:=%f", answerTableViewCell.frame.size.width);
    NSLog(@"tableView.frame.size.width:=%f", self.tableView.frame.size.width);
    NSLog(@"ivScreenshot.frame.width:=%f", ivScreenshot.frame.size.width);


    NSLog(@"answerTableViewCell.frame.size.width:=%f", answerTableViewCell.frame.size.width);
    NSLog(@"tableView.frame.size.width:=%f", self.tableView.frame.size.width);

    NSLog(@">>>>>>ivScreenshot.frame.size.width:%f", ivScreenshot.frame.size.width);
    NSLog(@">>>>>>ivScreenshot.frame.size.height:%f", ivScreenshot.frame.size.height);
    NSLog(@">>>>>>ivScreenshot.frame:height/width:%f", ivScreenshot.frame.size.height / ivScreenshot.frame.size.width);
//

    float scaleFactor = answerTableViewCell.frame.size.width / self.tableView.frame.size.width;
    NSLog(@"缩放比例参数为:%f", scaleFactor);
    //  float tmpHeight = ivScreenshot.frame.size.height;;

    NSLog(@"缩放处理之前的ivScreenshot宽度为:%f", ivScreenshot.frame.size.width);

    float frameWidth = ivScreenshot.frame.size.width / scaleFactor;
    NSLog(@"缩放处理后的ivScreenshot宽度为:%f", frameWidth);
    
    float frmameHeight = (frameWidth * question.resizedImageHeight) / question.resizedImageWidth;

    CGSize newSize = CGSizeMake(frameWidth, frmameHeight);

    NSLog(@"newSize.height:%f", newSize.height);

    answerTableViewCell.questionImageeLayoutFixHeightConstraint.constant = newSize.height;

    [self.view setNeedsLayout]; //更新视图
    [self.view layoutIfNeeded];


    //  ivScreenshot.image = [ImgeUtil imageWithImage:ivScreenshot.image scaledToSize:newSize];

    //CGRect oldRect = ivScreenshot.frame;




    // ivScreenshot.frame = CGRectMake(oldRect.origin.x, oldRect.origin.y, newSize.width, newSize.height);

    // oldRect = ivScreenshot.frame;

    NSLog(@"question.resizedImageHeight,frame.height=(%ld, %f)", question.resizedImageHeight, ivScreenshot.frame.size.height);

    [ivScreenshot layoutIfNeeded];
    [ivScreenshot updateConstraintsIfNeeded];
    [answerTableViewCell layoutSubviews];
    
    [answerTableViewCell layoutIfNeeded];
    [answerTableViewCell updateConstraintsIfNeeded];
    [answerTableViewCell layoutSubviews];


    [answerTableViewCell setAnswerImageWithURL:question.resizedImageUrl placeholderImage:@"loading" success:^(UIImage *image) {


        @try {


        }
        @catch (NSException *exception) {

            NSLog(@"exception:%@", exception);
        }

    }                                  failure:^(NSError *error) {

    }];
    float newHeight = answerTableViewCell.bounds.size.height + 1;
//   float newHeight=  answerTableViewCell.bounds.size.height -tmpHeight + newSize.height +1;
    NSString *strRowHeight = [NSString stringWithFormat:@"%f", newHeight];
    NSString *strRowNo = [NSString stringWithFormat:@"%ld", [indexPath row]];
    [self.rowHeightDictionary setObject:strRowHeight forKey:strRowNo];

    NSLog(@">>>>[ answerTableViewCell.bounds.size.height + 1]:%f", (answerTableViewCell.bounds.size.height + 1));

    return answerTableViewCell;
}


//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    NSString *strRowNo = [NSString stringWithFormat:@"%ld", [indexPath row]];
//    NSString *strRowHeight = [self.rowHeightDictionary objectForKey:strRowNo];
//
//    NSLog(@">>>>[strRowHeight intValue]:%f",[strRowHeight floatValue]);
//
//    return [strRowHeight floatValue];
//}


- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1.0f; // Add 1.0f for the cell separator height
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.didSelectedQuestion = self.answerPageModel.dataArray[indexPath.row];
    [self performSegueWithIdentifier:@"QuestionDetailSegueIdentifer" sender:self];
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([sender isKindOfClass:[QuestionTableViewCell class]]) {
        // prevent segue from occurring
        return NO;
    }
    // by default perform the segue transition
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"QuestionDetailSegueIdentifer"]) {
        QuestionDetailViewController *destination = segue.destinationViewController;
        [destination setQuestion:self.didSelectedQuestion];
    } else if ([segue.identifier isEqualToString:@"ToPostAnswerSegue"]) {
        PostAnswerViewController *destination = segue.destinationViewController;
        [destination setHelpId:self.didSelectedQuestion.questionId];;
    }
}

- (void)switchSelectSubjectShowView {
    //  NSLog(@"isViewSelectSubjectShow:%d",isViewSelectSubjectShow);
    BOOL tIsHidden = !isViewSelectSubjectShow;
    [self.viewSelectSubject setHidden:tIsHidden];
    [self.tableView setHidden:!tIsHidden];

    if (isViewSelectSubjectShow) {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_up_arrow"]];
    } else {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_down_arrow"]];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
